package mapper

import (
	"gin-epg/internal/app/dao"
	"gin-epg/internal/app/entity"
)

// CreateEpgProgram 创建一个新的 EpgProgram
func CreateEpgProgram(epgProgram *entity.EpgProgram) (err error) {
	if err = dao.SqlSession.Create(epgProgram).Error; err != nil {
		return err
	}
	return
}

/*
* 获取 EpgProgram 集合
 */
func GetAllEpgProgram() (epgProgramList []*entity.EpgProgram, err error) {
	if err := dao.SqlSession.Find(&epgProgramList).Error; err != nil {
		return nil, err
	}
	return
}

/*
* 根据 id 删除 EpgProgram
 */
func DeleteEpgProgramById(id string) (err error) {
	err = dao.SqlSession.Where("id=?", id).Delete(&entity.EpgProgram{}).Error
	return
}

/*
* 根据 id 查询 EpgProgram
 */
func GetEpgProgramById(id string) (epgProgram *entity.EpgProgram, err error) {
	// 初始化 epgProgram 变量
	epgProgram = new(entity.EpgProgram)

	// 执行查询
	if err = dao.SqlSession.Where("id=?", id).First(epgProgram).Error; err != nil {
		return nil, err
	}
	return epgProgram, nil
}

// GetEpgProgramByChDate 根据 ch 和 date 查询 EpgProgram 列表，并按 startTime 升序排序
func GetEpgProgramByChDate(ch string, date string) (epgPrograms []*entity.EpgProgram, err error) {
	// 初始化 epgPrograms 变量
	epgPrograms = make([]*entity.EpgProgram, 0)

	// 执行查询
	if err = dao.SqlSession.Where("channel=? AND date=?", ch, date).Order("start ASC").Find(&epgPrograms).Error; err != nil {
		return nil, err
	}
	return epgPrograms, nil
}

/*
* 更新 EpgProgram 信息
 */
func UpdateEpgProgram(epgProgram *entity.EpgProgram) (err error) {
	err = dao.SqlSession.Save(epgProgram).Error
	return
}
